package com.demo.io.bio.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @author libo
 * @version 1.0
 * @date 2018/5/29 10:24
 */
public class Client {

    private static final String IP = "127.0.0.1";
    private static final int PORT = 12345;

    public synchronized static void send() {
        send(PORT);
    }

    public synchronized static void send(int port) {
        Socket socket = null;
        BufferedReader br = null;
        PrintWriter pw = null;
        try {
            String text = "测试内容";
            System.out.println("向服务端发送：" + text);
            socket = new Socket(IP, port);
            pw = new PrintWriter(socket.getOutputStream(), true);
            pw.println(text);

            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String result = br.readLine();
            System.out.println("接收服务端消息：" + result);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
                pw = null;
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
